package com.wechat.user;

import cn.hutool.crypto.asymmetric.RSA;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

public class EncryptedRequestTester {
    
    private String gatewayUrl;
    private String publicKey;
    private RSA rsa;
    
    public EncryptedRequestTester(String gatewayUrl) {
        this.gatewayUrl = gatewayUrl;
        initPublicKey();
    }
    
    /**
     * 初始化公钥
     */
    private void initPublicKey() {
        try {
            String url = gatewayUrl + "/crypto/public-key";
            HttpResponse response = HttpRequest.get(url).execute();
            
            if (response.isOk()) {
                JSONObject result = JSONUtil.parseObj(response.body());
                JSONObject data = result.getJSONObject("data");
                this.publicKey = data.getStr("publicKey");
                this.rsa = cn.hutool.crypto.SecureUtil.rsa(null, publicKey);
                
                System.out.println("公钥获取成功: " + publicKey);
            } else {
                throw new RuntimeException("获取公钥失败: " + response.body());
            }
        } catch (Exception e) {
            throw new RuntimeException("初始化公钥失败", e);
        }
    }
    
    /**
     * 发送加密请求
     */
    public String sendEncryptedRequest(String path, Object data) {
        try {
            // 1. 序列化原始数据
            String plainText = JSONUtil.toJsonStr(data);
            System.out.println("原始数据: " + plainText);
            
            // 2. 加密数据
            String encryptedData = rsa.encryptBase64(plainText, cn.hutool.crypto.asymmetric.KeyType.PublicKey);
            System.out.println("加密数据: " + encryptedData);
            
            // 3. 构造请求体
            JSONObject request = new JSONObject();
            request.put("encrypted", true);
            request.put("data", encryptedData);
            request.put("timestamp", System.currentTimeMillis());
            
            // 4. 发送请求
            String url = gatewayUrl + path;
            HttpResponse response = HttpRequest.post(url)
                    .header("Content-Type", "application/json")
                    .body(request.toString())
                    .execute();
            
            System.out.println("响应状态: " + response.getStatus());
            System.out.println("响应内容: " + response.body());
            
            return response.body();
            
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    /**
     * 测试Hello接口
     */
    public static void main(String[] args) {
        EncryptedRequestTester tester = new EncryptedRequestTester("http://localhost:8080");
        
        // 测试数据
        JSONObject helloData = new JSONObject();
        helloData.put("name", "张三");
        
        // 发送加密请求
        tester.sendEncryptedRequest("/user/hello", helloData);
    }
}